/*
 * @Description:
 * @Author: Cxy
 * @Date: 2023-04-23 22:36:25
 * @LastEditors: Cxy
 * @LastEditTime: 2024-05-06 14:51:15
 * @FilePath: \blogAdmin\play\src\router\eachR.ts
 */
import type { Router } from 'vue-router'
import { powerStore } from '@/stores/power'
import { cookieRead } from '@/utils/storage'
import { labComCacheStore } from '@/stores/labComCache'

export default async (router: Router) => {
  router.beforeEach(async (to, from, next) => {
    if (!to.meta?.isShow && to.meta?.title && to.matched.length) {
      labComCacheStore.setCacheData(to.matched[to.matched.length - 1])
    }

    if (cookieRead('token')) {
      if (to.path === '/login') return next('/')
      if (!powerStore.allRD.length) {
        await powerStore.getPermissRouter()
        return next({ path: to.path, query: to.query, replace: true })
      }
      next()
    } else {
      if (to.path === '/login') return next()
      return next(`/login?path=${to.path}&query=${JSON.stringify(to.query)}`)
    }
  })
  router.afterEach((to, from) => {
    if (to.path === '/refresh') router.replace(from)
  })
}
